package network;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import bean.IResult;
import okhttp3.RequestBody;

/**
 * Created by sufutian on 2017/6/6.
 */

public abstract class BaseNetBuiness implements IDataSource.IDataSourceListener {


    private final String TAG = "BaseNetBuiness";

    private final int FAIL = 0, SUCCESS = 1, LOADING = 2;
    /**
     * 具体的数据回调
     */
    protected IBusinessListener<?> buinessListener;

    /**
     * 请求标识  get loadmore
     */
    private Object tag;
    /**
     * 回调业务结果的handler
     */
    final protected Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback() {

        @Override
        public boolean handleMessage(Message message) {
            if (buinessListener == null) {
                return true;
            }
            try {
                switch (message.what) {
                    case SUCCESS:
                        if (message.obj instanceof IResult)
                            ((IBusinessListener<IResult>) buinessListener).onLoadComplete((IResult) message.obj, getTag());
                        else
                            ((IBusinessListener<IJson>) buinessListener).onLoadComplete((IJson) message.obj, getTag());
                        break;
                    case FAIL:
                        Object[] objs = (Object[]) message.obj;
                        DataSourceErrorType type = (DataSourceErrorType) objs[0];
                        String error = (String) objs[1];
                        String json = (String) objs[2];
                        buinessListener.onLoadFailed(new DataSourceError(type, error, json), getTag());
                        break;
                    case LOADING:
                        buinessListener.onLoading(getTag());
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
    });


    /**
     * 初始化请求业务的 标识 回调
     *
     * @param tag
     * @param buinessListener
     */
    protected void initBusiness(Object tag, IBusinessListener<?> buinessListener) {
//        cancle(); //发起一个请求前  是否取消之前的请求
        setTag(tag);
        this.buinessListener = buinessListener;
    }

    /**
     * @param tag
     * @param buinessListener
     * @param cancle          是否 取消之前的所有请求
     */
    protected void initBusiness(Object tag, IBusinessListener<?> buinessListener, boolean cancle) {
        if (cancle) {
            cancle();
        }
        setTag(tag);
        this.buinessListener = buinessListener;
    }

    /**
     * 初始化 业务请求的 url 和 参数
     *
     * @param url
     * @param myJson
     */
    protected void initHttp(String url, MyJson myJson) {
        OkHttpEngine.getOkHttp().setDataSourceListener(this);
        OkHttpEngine.getOkHttp().seturl(url);
        OkHttpEngine.getOkHttp().setJson(myJson);
    }

    /**
     * get 请求
     *
     * @param url
     * @param myJson
     */
    protected void requestGet(String url, MyJson myJson) {
        initHttp(url, myJson);
        OkHttpEngine.getOkHttp().get();
    }

    /**
     * post json 请求
     *
     * @param url
     * @param myJson
     * @param
     */
    protected void requestPostJson(String url, MyJson myJson) {
        initHttp(url, myJson);
        OkHttpEngine.getOkHttp().post();
    }

    /**
     * post form 请求
     *
     * @param url
     * @param myJson
     * @param body
     */
    protected void requestPostForm(String url, MyJson myJson, RequestBody body) {
        initHttp(url, myJson);
        OkHttpEngine.getOkHttp().setBody(body);
        OkHttpEngine.getOkHttp().postForm();
    }


    @Override
    /**IDataSourceListener**/
    public void onLoading() {
        Message message = Message.obtain();
        message.what = LOADING;
        handler.sendMessage(message);
    }

    /**
     * OkHttpEngine 返回的json
     *
     * @param data 返回的数据
     */
    @Override
    /**IDataSourceListener**/
    public void onDataComplete(String data) {
        try {
            Log.e(TAG, "dataComplete->string:" + data);
            MyJson myJson = new MyJson(data);
            if (myJson.toString().length() <= 0) {
                onDataFail(DataSourceErrorType.data_error, "返回数据解析失败", "返回数据解析失败");
            } else {
                Log.e(TAG, "dataComplete->josn:" + myJson);
                int buinessCode = myJson.getInt("code");
                if (buinessCode == 0) {  // TODO: 2017/6/7  不同服务器处理方式不同
                    onDataFail(DataSourceErrorType.business_error, "没有数据", buinessCode + "");//服务器失败信息?
                } else if (buinessCode == -1) {
                    onDataFail(DataSourceErrorType.parameter_error, "来源错误(from值错误)", data);
                } else if (buinessCode == -2) {
                    onDataFail(DataSourceErrorType.parameter_error, "提交方式错误", data);
                } else if (buinessCode == -3) {
                    onDataFail(DataSourceErrorType.parameter_error, "参数错误", data);
                } else if (buinessCode == 1) { //成功 返回 json
                    onLoadComplete(myJson);
                } else {    //其他错误code
                    String errorMsg = "";
                    if (myJson.has("data")) {
                        errorMsg = myJson.getString("data");
                    }
                    onDataFail(DataSourceErrorType.parameter_error, errorMsg, buinessCode + "");
                }
            }

        } catch (Exception e) {
            onDataFail(DataSourceErrorType.data_error, "解析返回接口发生异常", data);
            Log.e(TAG, "解析返回接口发生异常");
        }
    }

    /**
     * 子类继承 去解析结果
     *
     * @param json
     */
    protected abstract void onLoadComplete(IJson json);

    /**
     * 解析完结果 post给handler
     *
     * @param result
     */
    protected void post(final Object result) {
        Message message = Message.obtain();
        message.obj = result;
        message.what = SUCCESS;
        handler.sendMessage(message);
    }


    @Override
    /**IDataSourceListener**/
    public void onDataFail(DataSourceErrorType type, String error, String json) {
        Message message = Message.obtain();
        message.obj = (new Object[]{type, error, json});
        message.what = FAIL;
        handler.sendMessage(message);
    }

    /**
     * 取消网络请求
     */
    public void cancle() {
        OkHttpEngine.getOkHttp().cancel();
    }


    public Object getTag() {
        return tag;
    }

    public void setTag(Object tag) {
        this.tag = tag;
    }
}
